package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.exception.BaseException;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 报表统计 业务实现类
 */
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    OrderMapper orderMapper;


    @Autowired
    UserMapper userMapper;


    /**
     * 统计指定时间内的营业额
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {

        //组织时间数据
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);//1-1
        while (begin.compareTo(end) < 0) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //组织营业额数据
        ArrayList<Double> turnoverList = new ArrayList<>();
        for (int i = 0; i < dateList.size(); i++) {
            LocalDate date = dateList.get(i);
            Double turnover = orderMapper.turnover(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
            turnoverList.add(turnover == null ? 0.0 : turnover);
        }

        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder().dateList(StringUtils.join(dateList, ",")).turnoverList(StringUtils.join(turnoverList, ",")).build();

        return turnoverReportVO;
    }

    /**
     * 新增用户数据统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {


        //组织时间数据
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);//1-1
        while (begin.compareTo(end) < 0) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //统计 当日新增用户  统计当日所有用户
        ArrayList<Integer> newUserList = new ArrayList<>();
        ArrayList<Integer> totalUserList = new ArrayList<>();

        for (int i = 0; i < dateList.size(); i++) {
            LocalDate date = dateList.get(i);
            HashMap<String, LocalDateTime> map = new HashMap<>();

            map.put("end", LocalDateTime.of(date, LocalTime.MAX));
            Integer totalCount = userMapper.countNewUser(map);
            totalUserList.add(totalCount);

            map.put("begin", LocalDateTime.of(date, LocalTime.MIN));
            Integer newCount = userMapper.countNewUser(map);

            newUserList.add(newCount);

        }

        UserReportVO userReportVO = UserReportVO.builder().dateList(StringUtils.join(dateList, ",")).newUserList(StringUtils.join(newUserList, ",")).totalUserList(StringUtils.join(totalUserList, ",")).build();
        return userReportVO;
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //组织时间数据
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);//1-1
        while (begin.compareTo(end) < 0) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //统计有效订单列表
        ArrayList<Integer> validOrderCountList = new ArrayList<>();
        //统计订单总数列表
        ArrayList<Integer> orderCountList = new ArrayList<>();
        for (int i = 0; i < dateList.size(); i++) {
            LocalDate date = dateList.get(i);
            HashMap<String, Object> map = new HashMap<>();
            map.put("begin", LocalDateTime.of(date, LocalTime.MIN));
            map.put("end", LocalDateTime.of(date, LocalTime.MAX));
            Integer totalCount = orderMapper.countStatusOrder(map);
            orderCountList.add(totalCount == null ? 0 : totalCount);
            map.put("status", Orders.COMPLETED);
            Integer validCount = orderMapper.countStatusOrder(map);
            validOrderCountList.add(validCount == null ? 0 : validCount);

        }


        //计算 有效订单总数
        Integer validCountAll = 0;
        for (int i = 0; i < validOrderCountList.size(); i++) {
            validCountAll += validOrderCountList.get(i);
        }
        //计算所有订单总数
        Integer totalCountAll = 0;
        for (int i = 0; i < orderCountList.size(); i++) {
            totalCountAll += orderCountList.get(i);
        }
        //计算 订单完成率
        Double orderCompletionTate = 0.0;
        if (totalCountAll != 0) {
            orderCompletionTate = validCountAll / (totalCountAll * 1.0);
        }
        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCount(validCountAll)
                .totalOrderCount(totalCountAll)
                .orderCompletionRate(orderCompletionTate).build();
        return orderReportVO;
    }

    /**
     * 统计销量前十的产品
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesVO> list = orderMapper.countTop10Goods(beginTime, endTime);
       /* ArrayList<String> namelist = new ArrayList<>();
        ArrayList<Integer> numberlist = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            GoodsSalesVO goodsSalesVO = list.get(i);
            namelist.add(goodsSalesVO.getName());
            numberlist.add(goodsSalesVO.getNumber());
        }*/
        List<String> namelist = list.stream().map(goodsSalesVO -> goodsSalesVO.getName()).collect(Collectors.toList());
        List<Integer> numberlist = list.stream().map(goodsSalesVO -> goodsSalesVO.getNumber()).collect(Collectors.toList());
        //统计菜品的名称

        //统计菜品的数量

        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(namelist, ","))
                .numberList(StringUtils.join(numberlist, ",")).build();
        return salesTop10ReportVO;
    }

    /**
     * 用户导出最近三天 数据报表
     */
    @Override
    public void export(HttpServletResponse response) {
        LocalDate end = LocalDate.now().plusDays(-1);
        LocalDate begin = LocalDate.now().plusDays(-30);

        //获取需要的数据
        BusinessDataVO businessDataVO = bussinessData(begin, end);
        FileInputStream fis = null;
        XSSFWorkbook excel = null;
        try {
            //fis = new FileInputStream("D:\\运营数据报表模板.xlsx");
            excel = new XSSFWorkbook(ClassLoader.getSystemResourceAsStream("运营数据报表模板.xlsx"));
            XSSFSheet sheet = excel.getSheetAt(0);
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            XSSFRow row4 = sheet.getRow(4);
            row4.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row4.getCell(4).setCellValue(businessDataVO.getUnitPrice());
            //每一天的营业额 有效订单数 订单完成率 平均客单价  新增用户数

            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);

                BusinessDataVO dateBusinessDateVO = bussinessData(date, date);


                XSSFRow row7 = sheet.getRow(7 + i);
                row7.getCell(1).setCellValue(date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                row7.getCell(2).setCellValue(dateBusinessDateVO.getTurnover());
                row7.getCell(3).setCellValue(dateBusinessDateVO.getValidOrderCount());
                row7.getCell(4).setCellValue(dateBusinessDateVO.getOrderCompletionRate());
                row7.getCell(5).setCellValue(dateBusinessDateVO.getUnitPrice());
                row7.getCell(6).setCellValue(dateBusinessDateVO.getNewUsers());
            }


            excel.write(response.getOutputStream());
        } catch (IOException e) {
            throw new BaseException("导出数据异常");
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                excel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    /**
     * 获取指定日期内的营业数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public BusinessDataVO bussinessData(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //近30天的 总营业额 ,总有效订单数 总 订单完成率 平均客单价  新增用户数
        Double turnover = orderMapper.turnover(beginTime, endTime);
        HashMap<String, Object> map = new HashMap<>();
        map.put("begin", beginTime);
        map.put("end", endTime);
        //近三十天的新增用户数
        Integer newUserCount = userMapper.countNewUser(map);
        //近三十天订单总数
        Integer totalCountAll = orderMapper.countStatusOrder(map);
        map.put("status", Orders.COMPLETED);
        //近三十天有效订单订单数
        Integer validCountAll = orderMapper.countStatusOrder(map);
        //近三十天的订单完成率
        Double orderCompletionTate = 0.0;
        //近三十天的客单价
        Double price = 0.0;
        if (totalCountAll != 0 && validCountAll != 0) {
            orderCompletionTate = (validCountAll == null ? 0 : validCountAll) / (totalCountAll * 1.0);
            price = (turnover == null ? 0 : turnover) / (validCountAll * 1.0);
        }

        BusinessDataVO businessDataVO = BusinessDataVO.builder()
                .turnover(turnover == null ? 0 : turnover)
                .validOrderCount(validCountAll == null ? 0 : validCountAll)
                .unitPrice(price)
                .newUsers(newUserCount == null ? 0 : newUserCount)
                .orderCompletionRate(orderCompletionTate)
                .build();

        return businessDataVO;
    }
}
